import React, { useState, useEffect } from 'react';
import {
  Card,
  Spin,
  Avatar,
  Tabs,
  Table,
  Tag,
  Button,
  Empty,
  message,
  Descriptions,
  Space,
  Tooltip,
  Divider
} from 'antd';
import {
  UserOutlined,
  PhoneOutlined,
  MailOutlined,
  HomeOutlined,
  MedicineBoxOutlined,
  AlertOutlined,
  FileTextOutlined,
  PrinterOutlined,
  EditOutlined
} from '@ant-design/icons';
import { useParams } from 'react-router-dom';
import './index.less';

// 定义接口
interface VisitRecord {
  id: string;
  date: string;
  department: string;
  doctor: string;
  diagnosis: string;
  status: 'active' | 'completed' | 'cancelled';
}

interface TestResult {
  id: string;
  date: string;
  name: string;
  type: string;
  result: string;
  normalRange?: string;
  status: 'normal' | 'abnormal' | 'critical';
}

interface Medication {
  id: string;
  name: string;
  dosage: string;
  frequency: string;
  startDate: string;
  endDate?: string;
  status: 'active' | 'completed' | 'discontinued';
}

interface Allergy {
  id: string;
  allergen: string;
  reaction: string;
  severity: 'mild' | 'moderate' | 'severe';
  identified: string;
}

interface PatientInfo {
  id: string;
  name: string;
  gender: string;
  age: number;
  birthDate: string;
  idNumber: string;
  mrn: string;
  phone: string;
  email?: string;
  address: string;
  bloodType?: string;
  insuranceType?: string;
  insuranceNumber?: string;
}

const statusColors = {
  active: 'green',
  completed: 'blue',
  cancelled: 'red',
  discontinued: 'red',
  normal: 'green',
  abnormal: 'orange',
  critical: 'red',
  mild: 'green',
  moderate: 'orange',
  severe: 'red',
};

const Patient360Detail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [loading, setLoading] = useState<boolean>(true);
  const [patientInfo, setPatientInfo] = useState<PatientInfo | null>(null);
  const [visitRecords, setVisitRecords] = useState<VisitRecord[]>([]);
  const [testResults, setTestResults] = useState<TestResult[]>([]);
  const [medications, setMedications] = useState<Medication[]>([]);
  const [allergies, setAllergies] = useState<Allergy[]>([]);

  useEffect(() => {
    // 模拟获取患者数据
    const fetchPatientData = async () => {
      try {
        // 实际项目中这里应该调用API
        setTimeout(() => {
          // 基本信息
          setPatientInfo({
            id: '1001',
            name: '张三',
            gender: '男',
            age: 45,
            birthDate: '1979-05-12',
            idNumber: '110101197905123456',
            mrn: 'MRN10012345',
            phone: '13800138000',
            email: 'zhangsan@example.com',
            address: '北京市海淀区中关村大街123号',
            bloodType: 'A+',
            insuranceType: '城镇职工医保',
            insuranceNumber: 'INS2023001'
          });

          // 诊疗记录
          setVisitRecords([
            {
              id: 'V001',
              date: '2023-10-15',
              department: '内科',
              doctor: '李医生',
              diagnosis: '高血压, 2型糖尿病',
              status: 'completed'
            },
            {
              id: 'V002',
              date: '2023-12-05',
              department: '内分泌科',
              doctor: '王医生',
              diagnosis: '糖尿病随访',
              status: 'completed'
            },
            {
              id: 'V003',
              date: '2024-02-20',
              department: '心血管内科',
              doctor: '郑医生',
              diagnosis: '心绞痛',
              status: 'active'
            }
          ]);

          // 检验检查结果
          setTestResults([
            {
              id: 'T001',
              date: '2024-02-20',
              name: '血常规',
              type: '检验',
              result: '白细胞计数偏高',
              normalRange: '4.0-10.0 x10^9/L',
              status: 'abnormal'
            },
            {
              id: 'T002',
              date: '2024-02-20',
              name: '血糖',
              type: '检验',
              result: '7.8 mmol/L',
              normalRange: '3.9-6.1 mmol/L',
              status: 'abnormal'
            },
            {
              id: 'T003',
              date: '2024-02-20',
              name: '心电图',
              type: '检查',
              result: '窦性心律, ST段轻度下降',
              status: 'abnormal'
            },
            {
              id: 'T004',
              date: '2023-12-05',
              name: '糖化血红蛋白',
              type: '检验',
              result: '6.8%',
              normalRange: '4.0-6.0%',
              status: 'abnormal'
            }
          ]);

          // 用药记录
          setMedications([
            {
              id: 'M001',
              name: '复方降压片',
              dosage: '1片',
              frequency: '每日2次',
              startDate: '2023-10-15',
              status: 'active'
            },
            {
              id: 'M002',
              name: '二甲双胍',
              dosage: '0.5g',
              frequency: '每日3次',
              startDate: '2023-10-15',
              status: 'active'
            },
            {
              id: 'M003',
              name: '阿司匹林',
              dosage: '100mg',
              frequency: '每日1次',
              startDate: '2024-02-20',
              status: 'active'
            },
            {
              id: 'M004',
              name: '抗生素',
              dosage: '0.5g',
              frequency: '每日3次',
              startDate: '2023-08-10',
              endDate: '2023-08-17',
              status: 'completed'
            }
          ]);

          // 过敏信息
          setAllergies([
            {
              id: 'A001',
              allergen: '青霉素',
              reaction: '皮疹, 瘙痒',
              severity: 'moderate',
              identified: '2015-03-12'
            },
            {
              id: 'A002',
              allergen: '海鲜',
              reaction: '荨麻疹',
              severity: 'mild',
              identified: '2010-06-20'
            }
          ]);

          setLoading(false);
        }, 1500); // 模拟API请求延迟
      } catch (error) {
        message.error('获取患者数据失败');
        setLoading(false);
      }
    };

    fetchPatientData();
  }, [id]);

  // 定义表格列
  const visitColumns = [
    {
      title: '就诊日期',
      dataIndex: 'date',
      key: 'date',
    },
    {
      title: '科室',
      dataIndex: 'department',
      key: 'department',
    },
    {
      title: '医生',
      dataIndex: 'doctor',
      key: 'doctor',
    },
    {
      title: '诊断',
      dataIndex: 'diagnosis',
      key: 'diagnosis',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={statusColors[status] || 'default'}>
          {status === 'active' ? '进行中' : status === 'completed' ? '已完成' : '已取消'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record: VisitRecord) => (
        <Space size="middle">
          <a onClick={() => message.info(`查看就诊记录 ${record.id}`)}>查看详情</a>
        </Space>
      ),
    },
  ];

  const testResultColumns = [
    {
      title: '检查日期',
      dataIndex: 'date',
      key: 'date',
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '结果',
      dataIndex: 'result',
      key: 'result',
    },
    {
      title: '参考范围',
      dataIndex: 'normalRange',
      key: 'normalRange',
      render: (normalRange: string) => normalRange || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={statusColors[status] || 'default'}>
          {status === 'normal' ? '正常' : status === 'abnormal' ? '异常' : '危急'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record: TestResult) => (
        <Space size="middle">
          <a onClick={() => message.info(`查看检查结果 ${record.id}`)}>查看详情</a>
        </Space>
      ),
    },
  ];

  const medicationColumns = [
    {
      title: '药品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '剂量',
      dataIndex: 'dosage',
      key: 'dosage',
    },
    {
      title: '频次',
      dataIndex: 'frequency',
      key: 'frequency',
    },
    {
      title: '开始日期',
      dataIndex: 'startDate',
      key: 'startDate',
    },
    {
      title: '结束日期',
      dataIndex: 'endDate',
      key: 'endDate',
      render: (endDate: string) => endDate || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={statusColors[status] || 'default'}>
          {status === 'active' ? '使用中' : status === 'completed' ? '已结束' : '已停用'}
        </Tag>
      ),
    },
  ];

  const allergyColumns = [
    {
      title: '过敏原',
      dataIndex: 'allergen',
      key: 'allergen',
    },
    {
      title: '反应',
      dataIndex: 'reaction',
      key: 'reaction',
    },
    {
      title: '严重程度',
      dataIndex: 'severity',
      key: 'severity',
      render: (severity: string) => (
        <Tag color={statusColors[severity] || 'default'}>
          {severity === 'mild' ? '轻度' : severity === 'moderate' ? '中度' : '重度'}
        </Tag>
      ),
    },
    {
      title: '确认日期',
      dataIndex: 'identified',
      key: 'identified',
    },
  ];

  if (loading) {
    return (
      <div className="patient360-detail-container" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
        <Spin size="large" tip="加载患者数据中..." />
      </div>
    );
  }

  if (!patientInfo) {
    return (
      <div className="patient360-detail-container">
        <Empty description="未找到患者数据" />
      </div>
    );
  }

  return (
    <div className="patient360-detail-container">
      {/* 页面标题 */}
      <div className="page-header">
        <div className="header-title">患者360°详情</div>
        <div className="header-actions">
          <Button icon={<EditOutlined />}>编辑信息</Button>
          <Button icon={<PrinterOutlined />} type="primary">打印报告</Button>
        </div>
      </div>

      {/* 患者基本信息 */}
      <Card className="patient-info-section">
        <div className="patient-header">
          <div className="patient-avatar">
            <Avatar size={80} icon={<UserOutlined />} />
          </div>
          <div className="patient-basic">
            <div className="patient-name">{patientInfo.name} ({patientInfo.gender}, {patientInfo.age}岁)</div>
            <div className="patient-ids">
              <div className="id-item">
                <span className="label">身份证号:</span>
                <span className="value">{patientInfo.idNumber}</span>
              </div>
              <div className="id-item">
                <span className="label">病历号:</span>
                <span className="value">{patientInfo.mrn}</span>
              </div>
              <div className="id-item">
                <span className="label">血型:</span>
                <span className="value">{patientInfo.bloodType || '未知'}</span>
              </div>
              <div className="id-item">
                <span className="label">出生日期:</span>
                <span className="value">{patientInfo.birthDate}</span>
              </div>
            </div>
            <div className="patient-contact">
              <div className="contact-item">
                <PhoneOutlined className="icon" />
                <span className="value">{patientInfo.phone}</span>
              </div>
              {patientInfo.email && (
                <div className="contact-item">
                  <MailOutlined className="icon" />
                  <span className="value">{patientInfo.email}</span>
                </div>
              )}
              <div className="contact-item">
                <HomeOutlined className="icon" />
                <span className="value">{patientInfo.address}</span>
              </div>
            </div>
          </div>
        </div>

        <Divider />

        <div className="health-summary">
          <h4>健康概要</h4>
          <div className="summary-item">
            <h3><MedicineBoxOutlined /> 当前用药 ({medications.filter(med => med.status === 'active').length})</h3>
            <div className="summary-content">
              {medications.filter(med => med.status === 'active').map(med => (
                <div key={med.id} className="med-item">
                  <Tag color="blue">{med.name}</Tag>
                  <span>{med.dosage}, {med.frequency}, 始于 {med.startDate}</span>
                </div>
              ))}
              {medications.filter(med => med.status === 'active').length === 0 && <Empty description="无当前用药" />}
            </div>
          </div>
          <div className="summary-item">
            <h3><AlertOutlined /> 过敏信息 ({allergies.length})</h3>
            <div className="summary-content">
              {allergies.map(allergy => (
                <div key={allergy.id} className="med-item">
                  <Tag color={statusColors[allergy.severity]}>{allergy.allergen}</Tag>
                  <span>{allergy.reaction}, {allergy.severity === 'mild' ? '轻度' : allergy.severity === 'moderate' ? '中度' : '重度'}</span>
                </div>
              ))}
              {allergies.length === 0 && <Empty description="无过敏记录" />}
            </div>
          </div>
          <div className="summary-item">
            <h3><FileTextOutlined /> 保险信息</h3>
            <div className="summary-content">
              <Descriptions column={2}>
                <Descriptions.Item label="保险类型">{patientInfo.insuranceType || '无'}</Descriptions.Item>
                <Descriptions.Item label="保险号">{patientInfo.insuranceNumber || '无'}</Descriptions.Item>
              </Descriptions>
            </div>
          </div>
        </div>
      </Card>

      {/* 详细记录标签页 */}
      <Card>
        <Tabs defaultActiveKey="visits">
          <Tabs.TabPane tab="就诊记录" key="visits">
            <Table
              columns={visitColumns}
              dataSource={visitRecords}
              rowKey="id"
              pagination={{ pageSize: 5 }}
            />
          </Tabs.TabPane>
          <Tabs.TabPane tab="检验检查结果" key="tests">
            <Table
              columns={testResultColumns}
              dataSource={testResults}
              rowKey="id"
              pagination={{ pageSize: 5 }}
            />
          </Tabs.TabPane>
          <Tabs.TabPane tab="用药记录" key="medications">
            <Table
              columns={medicationColumns}
              dataSource={medications}
              rowKey="id"
              pagination={{ pageSize: 5 }}
            />
          </Tabs.TabPane>
          <Tabs.TabPane tab="过敏信息" key="allergies">
            <Table
              columns={allergyColumns}
              dataSource={allergies}
              rowKey="id"
              pagination={{ pageSize: 5 }}
            />
          </Tabs.TabPane>
        </Tabs>
      </Card>
    </div>
  );
};

export default Patient360Detail; 
